import smtplib
from email.header import Header
from email.mime.text import MIMEText


class Mail:
    def __init__(self, mail_pass, sender, receivers):
        # 第三方 SMTP 服务
        self.mail_host = "smtp.qq.com"  # 填写邮箱服务器:这个是qq邮箱服务器，直接使用smtp.qq.com
        self.mail_pass = mail_pass  # 填写在qq邮箱设置中获取的授权码
        self.sender = sender  # 填写邮箱地址
        self.receivers = receivers  # 填写收件人的邮箱，QQ邮箱或者其他邮箱，可多个，中间用,隔开

    def send(self, subject, content):
        message = MIMEText(content, 'plain', 'utf-8')  # 邮件内容

        message['From'] = Header(self.sender)  # 邮件发送者姓名
        # message['To'] = Header(self.receivers)  # 邮件接收者姓名

        message['Subject'] = Header(subject, 'utf-8')  # 发送的主题

        print(message)

        try:
            smtpObj = smtplib.SMTP_SSL(self.mail_host, 465)  # 建立smtp连接，qq邮箱必须用ssl边接，因此边接465端口
            smtpObj.login(self.sender, self.mail_pass)  # 登陆
            smtpObj.sendmail(self.sender, self.receivers, message.as_string())  # 发送
            smtpObj.quit()
            print(f"发送成功：sender：{self.sender} receivers:{self.receivers}")
        except smtplib.SMTPException as e:
            print(f"发送失败：sender：{self.sender} receivers:{self.receivers} ，失败原因：{e}")


if __name__ == '__main__':
    mail = Mail("vbgbznzwogehdjde", "2549185598@qq.com", ["2549185598@qq.com"])
    mail.send("titel", "content")